<template>
  <v-app>
    <v-main>
      <v-container fluid class="fill-height">
        <v-row justify="center" align="center" class="fill-height">
          <v-col cols="12" sm="8" md="6" lg="4" xl="3">
            <v-card class="login-card" elevation="8">
              <v-card-title class="text-center py-8">
                <div class="logo-section">
                  <v-icon size="64" color="primary" class="mb-4">mdi-school</v-icon>
                  <h1 class="text-h4 font-weight-bold text-primary">Newton</h1>
                  <p class="text-subtitle-1 text-medium-emphasis">校园考勤系统</p>
                </div>
              </v-card-title>

              <v-card-text class="px-8 pb-8">
                <v-form ref="loginForm" @submit.prevent="handleLogin">
                  <v-text-field
                    v-model="form.username"
                    :label="$t('auth.username')"
                    :rules="usernameRules"
                    prepend-inner-icon="mdi-account"
                    variant="outlined"
                    density="comfortable"
                    class="mb-4"
                    required
                  ></v-text-field>

                  <v-text-field
                    v-model="form.password"
                    :label="$t('auth.password')"
                    :rules="passwordRules"
                    :type="showPassword ? 'text' : 'password'"
                    prepend-inner-icon="mdi-lock"
                    :append-inner-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
                    @click:append-inner="showPassword = !showPassword"
                    variant="outlined"
                    density="comfortable"
                    class="mb-6"
                    required
                  ></v-text-field>

                  <v-btn
                    type="submit"
                    color="primary"
                    size="large"
                    block
                    :loading="authStore.loading"
                    :disabled="!isFormValid"
                    class="mb-4"
                  >
                    {{ $t('auth.login') }}
                  </v-btn>

                  <!-- 演示账号 -->
                  <v-divider class="my-4"></v-divider>            
                </v-form>
              </v-card-text>
            </v-card>

            <!-- 语言切换 -->
            <div class="text-center mt-4">
              <v-btn-toggle
                v-model="currentLanguage"
                mandatory
                variant="outlined"
                divided
                @update:model-value="changeLanguage"
              >
                <v-btn value="zh" size="small">中文</v-btn>
                <v-btn value="en" size="small">English</v-btn>
              </v-btn-toggle>
            </div>
          </v-col>
        </v-row>
      </v-container>
    </v-main>

    <!-- 错误提示 -->
    <v-snackbar
      v-model="error.show"
      color="error"
      location="top"
      :timeout="4000"
    >
      {{ error.message }}
      <template v-slot:actions>
        <v-btn
          color="white"
          variant="text"
          @click="error.show = false"
        >
          关闭
        </v-btn>
      </template>
    </v-snackbar>
  </v-app>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const { locale, t } = useI18n()
const authStore = useAuthStore()

// 响应式数据
const loginForm = ref(null)
const showPassword = ref(false)
const currentLanguage = ref('zh')
const form = ref({
  username: '',
  password: ''
})

const error = ref({
  show: false,
  message: ''
})

// 验证规则
const usernameRules = [
  v => !!v || t('auth.usernameRequired'),
  v => v.length >= 3 || '用户名至少3位'
]

const passwordRules = [
  v => !!v || t('auth.passwordRequired'),
  v => v.length >= 6 || '密码至少6位'
]

// 计算属性
const isFormValid = computed(() => {
  return form.value.username.length >= 3 && form.value.password.length >= 6
})

// 演示账号配置
const demoAccounts = {
  admin: { username: 'admin', password: '123456' },
  teacher: { username: 'teacher001', password: '123456' },
  driver: { username: 'driver001', password: '123456' }
}

// 方法
const handleLogin = async () => {
  const { valid } = await loginForm.value.validate()
  if (!valid) return

  const result = await authStore.login(form.value)
  
  if (result.success) {
    // 登录成功，根据角色跳转到对应页面
    const role = result.data.role
    if (role === 'admin') {
      router.push('/admin/dashboard')
    } else if (role === 'teacher') {
      router.push('/teacher/dashboard')
    } else if (role === 'driver') {
      router.push('/driver/departure')
    } else {
      router.push('/')
    }
  } else {
    showError(result.message)
  }
}

const setDemoAccount = (type) => {
  const account = demoAccounts[type]
  form.value.username = account.username
  form.value.password = account.password
}

const changeLanguage = (langCode) => {
  if (langCode) {
    locale.value = langCode
    localStorage.setItem('language', langCode)
  }
}

const showError = (message) => {
  error.value = {
    show: true,
    message
  }
}

// 生命周期
onMounted(() => {
  // 如果已经登录，重定向到对应页面
  if (authStore.isAuthenticated) {
    const role = authStore.userRole
    if (role === 'admin') {
      router.push('/admin/dashboard')
    } else if (role === 'teacher') {
      router.push('/teacher/dashboard')
    } else if (role === 'driver') {
      router.push('/driver/departure')
    }
  }

  // 恢复语言设置
  const savedLang = localStorage.getItem('language')
  if (savedLang) {
    currentLanguage.value = savedLang
    locale.value = savedLang
  }
})
</script>

<style scoped>
.fill-height {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  position: relative;
}

.fill-height::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(120, 119, 198, 0.05) 0%, transparent 50%);
}

.login-card {
  border-radius: 20px;
  backdrop-filter: blur(20px);
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1), 0 0 0 1px rgba(255, 255, 255, 0.05);
  position: relative;
  z-index: 1;
}

.logo-section {
  text-align: center;
}

.logo-section h1 {
  background: linear-gradient(135deg, #1e293b, #475569);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.demo-accounts .v-btn {
  height: 32px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.demo-accounts .v-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 600px) {
  .login-card {
    margin: 16px;
  }
  
  .v-card-title {
    padding: 24px 16px !important;
  }
  
  .v-card-text {
    padding: 0 16px 24px !important;
  }
}

/* 动画效果 */
.login-card {
  animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 输入框聚焦效果 */
.v-text-field:hover :deep(.v-field__outline) {
  color: rgba(var(--v-theme-primary), 0.7);
}

.v-btn-toggle {
  border-radius: 8px;
  overflow: hidden;
}
</style>
